 //
//  YHOAuthController.swift
//  WeiBoYH
//
//  Created by yanhui on 2017/1/8.
//  Copyright © 2017年 yanhui. All rights reserved.
//

import UIKit
import SVProgressHUD

class YHOAuthController: UIViewController{

    let webView = UIWebView()
    
    
    @objc private func close(){
        dismiss(animated: true, completion: nil)
        
        
    }
    @objc private func devAccount(){
        let jsString = "document.getElementById('userId').value = '13585995657',document.getElementById('passwd').value = 'hou80127713' "
        
      webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        
        //设置关闭按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭" , target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "走后门" , target: self, action: #selector(devAccount))
        
        loadOAuthPage()
    
    }

    private func loadOAuthPage(){
         let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
       webView.loadRequest(req)
     
        
    }
  
  
}

 //在分类中实现某一个协议中需要实现的方法
 extension YHOAuthController: UIWebViewDelegate {
    
    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        //show 指示器
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //        dismiss 指示器
        SVProgressHUD.dismiss()
    }
    //截取code
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code="
        if urlString.contains(flag){
            
            //url的参数部分
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            //通过code获取令牌
            YHUserAccountViewModel.shard.loadAccessToken(code: code, finished: { (success) in
                if !success {
                    //如果没有成功
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
                
                print("用户登录成功")
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name.AppChangeRootVc, object: "YHWelcomeViewController")
            })
            
    //在移动应用中不需要加载授权回调页面
            return false
        }
        return true
    }
    

 }

